package cn.kgc.crowdfundingadmin03.service;

import cn.kgc.crowdfundingadmin03.common.CrowdFundingUtils;
import cn.kgc.crowdfundingadmin03.mapper.AdminMapper;
import cn.kgc.crowdfundingadmin03.mapper.AuthMapper;
import cn.kgc.crowdfundingadmin03.mapper.RoleMapper;
import cn.kgc.crowdfundingadmin03.pojo.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shkstart
 * @create 2020-03-09 21:08
 */
@Service
public class CrowdUserDetailsService implements UserDetailsService {

    @Resource
    AdminMapper adminMapper;

    @Resource
    RoleMapper roleMapper;
    @Resource
    AuthMapper authMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        AdminExample example=new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andLoginacctEqualTo(s);

        List<Admin> admins = adminMapper.selectByExample(example);
                    //如果 admins不能空 则查找数据
                if (CrowdFundingUtils.collectionEffective(admins)){
                    Admin admin=admins.get(0);//从第一个开始查询 所有初始为0

                    //封装角色和权限的集合  创建集合
                    List<GrantedAuthority> authorities=new ArrayList<>();

                    //获取角色对象
                    List<Role> roleList= roleMapper.getAssignedRoleList(admin.getId());

                    //存储角色id,用于权限查询
                    List<Integer> authIdList=new ArrayList<>();

                    //如果该角色有权限的话 则输出
                    if(CrowdFundingUtils.collectionEffective(roleList)){
                        for (Role role : roleList) {
                            //输出权限名称
                            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
                            //存储权限的id
                            authIdList.add(role.getId());
                        }
                    }

                    //存储权限
                    List<Auth> authList=authMapper.selectByRoleIds(authIdList);
                    if(CrowdFundingUtils.collectionEffective(authIdList)){
                        for (Auth auth : authList) {
                            if(CrowdFundingUtils.stringEffective(auth.getName())){
                                authorities.add(new SimpleGrantedAuthority(auth.getName()));
                            }
                        }
                    }

            //封装角色和权限信息
          return new SecurityAdmin(admin, authorities );
                }else {
                    return null;
                }

    }
}
